<template>
  <div class="glass-dashboard-home">
    <!-- Dashboard Header -->
    <div class="dashboard-header glass-card">
      <div class="header-content">
        <!-- Welcome Section -->
        <div class="welcome-section glass-card">
          <div class="welcome-content">
            <div class="welcome-info">
              <div class="welcome-text">
                <h1>Good Morning, Admin</h1>
                <p class="welcome-date">{{ getCurrentDate() }}</p>
              </div>
            </div>
            <!-- Leave Status Notifications -->
            <div class="leave-notifications">
              <div class="notification-header">
                <div class="notification-title">
                  <svg-icon icon-class="bell" class="notification-icon" />
                  <span>通知信息</span>
                </div>
                <div class="notification-count" v-if="leaveNotifications.length > 0">{{ leaveNotifications.length }}</div>
              </div>
              <div class="notification-list" v-if="leaveNotifications.length > 0">
                <div 
                  v-for="notification in leaveNotifications" 
                  :key="notification.id"
                  class="notification-item glass-card glass-card--sm"
                  :class="notification.type"
                >
                  <div class="notification-content">
                    <div class="notification-message">
                      <svg-icon :icon-class="notification.icon" class="message-icon" />
                      <span>{{ notification.message }}</span>
                    </div>
                    <div class="notification-actions">
                      <button 
                        class="glass-button glass-button--sm glass-button--primary"
                        @click="handleStatusUpdate(notification)"
                      >
                        {{ notification.actionText }}
                      </button>
                      <button 
                        class="glass-button glass-button--sm"
                        @click="dismissNotification(notification.id)"
                      >
                        忽略
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 无通知时的空状态 -->
              <div class="notification-empty" v-else>
                <div class="empty-content">
                  <svg-icon icon-class="check" class="empty-icon" />
                  <p class="empty-text">暂无通知</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>


    <!-- Charts Section -->
    <div class="charts-grid">
      <div class="chart-card glass-card">
        <div class="chart-header">
          <div class="chart-title">
            <div class="title-icon">
              <svg-icon icon-class="monitor" />
            </div>
            <div class="title-content">
              <h3>隐患状态分布</h3>
              <p>Issue Status Distribution</p>
            </div>
          </div>
          <div class="chart-actions">
            <button class="glass-button glass-button--sm" @click="refreshData">
              <svg-icon icon-class="refresh" />
            </button>
          </div>
        </div>
        <div class="status-overview">
          <div class="overview-grid">
            <div class="overview-item overview-item--danger">
              <div class="item-header">
                <div class="item-icon">
                  <svg-icon icon-class="bug" />
                </div>
                <div class="item-trend">
                  <span class="trend-indicator trend-up">{{ getStatusPercentage(0) }}%</span>
                </div>
              </div>
              <div class="item-content">
                <div class="item-number">{{ getStatusCount(0) }}</div>
                <div class="item-label">待维修隐患</div>
                <div class="item-desc">Pending Repair</div>
              </div>
            </div>
            
            <div class="overview-item overview-item--warning">
              <div class="item-header">
                <div class="item-icon">
                  <svg-icon icon-class="time" />
                </div>
                <div class="item-trend">
                  <span class="trend-indicator trend-stable">{{ getStatusPercentage(2) }}%</span>
                </div>
              </div>
              <div class="item-content">
                <div class="item-number">{{ getStatusCount(2) }}</div>
                <div class="item-label">待审核隐患</div>
                <div class="item-desc">Under Review</div>
              </div>
            </div>
            
            <div class="overview-item overview-item--success">
              <div class="item-header">
                <div class="item-icon">
                  <svg-icon icon-class="star" />
                </div>
                <div class="item-trend">
                  <span class="trend-indicator trend-down">{{ getStatusPercentage(1) }}%</span>
                </div>
              </div>
              <div class="item-content">
                <div class="item-number">{{ getStatusCount(1) }}</div>
                <div class="item-label">已解决隐患</div>
                <div class="item-desc">Resolved</div>
              </div>
            </div>
            
            <div class="overview-item overview-item--info">
              <div class="item-header">
                <div class="item-icon">
                  <svg-icon icon-class="delete" />
                </div>
                <div class="item-trend">
                  <span class="trend-indicator trend-neutral">{{ getStatusPercentage(3) }}%</span>
                </div>
              </div>
              <div class="item-content">
                <div class="item-number">{{ getStatusCount(3) }}</div>
                <div class="item-label">不通过隐患</div>
                <div class="item-desc">Rejected</div>
              </div>
            </div>
          </div>
          
          <div class="overview-summary">
            <div class="summary-item">
              <div class="summary-label">处理效率</div>
              <div class="summary-value">{{ getProcessingRate() }}%</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">解决率</div>
              <div class="summary-value">{{ getResolutionRate() }}%</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">总计隐患</div>
              <div class="summary-value">{{ statistics.totalCount }}</div>
            </div>
          </div>
          
          <div class="chart-footer">
            <div class="data-info">
              <svg-icon icon-class="info" class="info-icon" />
              <span>实时状态分布统计</span>
            </div>
          </div>
        </div>
      </div>

      <div class="chart-card glass-card">
        <div class="chart-header">
          <div class="chart-title">
            <div class="title-icon">
              <svg-icon icon-class="star" />
            </div>
            <div class="title-content">
              <h3>月度隐患趋势</h3>
              <p>Monthly Trend Analysis</p>
            </div>
          </div>
          <div class="chart-actions">
            <button class="glass-button glass-button--sm" @click="refreshData">
              <svg-icon icon-class="refresh" />
            </button>
          </div>
        </div>
        <div class="chart-container">
          <div ref="trendChart" class="chart-content"></div>
          <div class="chart-footer">
            <div class="data-info">
              <svg-icon icon-class="info" class="info-icon" />
              <span>最近6个月趋势分析</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Content Grid -->
    <div class="content-grid">
      <!-- Recent Issues List -->
      <div class="issues-section glass-card">
        <div class="section-header">
          <div class="section-title">
            <div class="title-icon">
              <svg-icon icon-class="bug" />
            </div>
            <div class="title-content">
              <h3>最新安全隐患</h3>
              <p>Recent Safety Issues</p>
            </div>
          </div>
          <div class="section-actions">
            <button class="glass-button glass-button--primary" @click="goToInformation">
              <svg-icon icon-class="search" />
              <span>查看全部</span>
            </button>
          </div>
        </div>
        
        <div class="issues-list" v-loading="loading">
          <div v-if="latestIssues.length === 0" class="empty-state">
            <svg-icon icon-class="document" class="empty-icon" />
            <p>暂无安全隐患记录</p>
          </div>
          <div v-else class="issue-items">
            <div 
              v-for="issue in latestIssues.slice(0, 6)" 
              :key="issue.id" 
              class="issue-item glass-card glass-card--sm"
              @click="viewDetail(issue)"
            >
              <div class="issue-header">
                <div class="issue-id">#{{ issue.id }}</div>
                <div class="issue-status">
                  <span :class="['status-badge', `status-${issue.status}`]">
                    {{ getStatusText(issue.status) }}
                  </span>
                </div>
              </div>
              <div class="issue-content">
                <div class="issue-region">
                  <svg-icon icon-class="location" class="region-icon" />
                  <span>{{ getRegionName(issue.regionId) }}</span>
                </div>
                <div class="issue-time">
                  <svg-icon icon-class="time" class="time-icon" />
                  <span>{{ formatTime(issue.detectionTime) }}</span>
                </div>
              </div>
              <div class="issue-footer" v-if="issue.remarks">
                <p class="issue-remark">{{ issue.remarks }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Quick Actions Panel -->
      <div class="actions-section glass-card">
        <div class="section-header">
          <div class="section-title">
            <div class="title-icon">
              <svg-icon icon-class="system" />
            </div>
            <div class="title-content">
              <h3>快速操作</h3>
              <p>Quick Actions</p>
            </div>
          </div>
        </div>
        
        <div class="action-items">
          <div class="action-item glass-card glass-card--sm" @click="goToInformation">
            <div class="action-icon action-icon--search">
              <svg-icon icon-class="search" />
            </div>
            <div class="action-content">
              <h4>隐患查询</h4>
              <p>Issue Search</p>
            </div>
            <div class="action-arrow">
              <svg-icon icon-class="arrow-right" />
            </div>
          </div>
          
          <div class="action-item glass-card glass-card--sm" @click="exportData">
            <div class="action-icon action-icon--export">
              <svg-icon icon-class="download" />
            </div>
            <div class="action-content">
              <h4>导出数据</h4>
              <p>Export Data</p>
            </div>
            <div class="action-arrow">
              <svg-icon icon-class="arrow-right" />
            </div>
          </div>
          
          <div class="action-item glass-card glass-card--sm" @click="goToMenuManagement">
            <div class="action-icon action-icon--settings">
              <svg-icon icon-class="system" />
            </div>
            <div class="action-content">
              <h4>系统设置</h4>
              <p>System Settings</p>
            </div>
            <div class="action-arrow">
              <svg-icon icon-class="arrow-right" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Index">
import { listInformation } from '@/api/information/information'
import { listRegion } from '@/api/region/region'
import { listLeave, updateLeave } from '@/api/leave/leave'
import { listUser, updateUser } from '@/api/system/user'
import * as echarts from 'echarts'

const { proxy } = getCurrentInstance()
const loading = ref(false)
const latestIssues = ref([])
const regionList = ref([])
const monthlyData = ref({})
const trendChart = ref(null)

// 请假通知相关数据
const leaveNotifications = ref([])
const userList = ref([])
const leaveList = ref([])
const dismissedNotifications = ref(new Set())

// 统计数据
const statistics = ref({
  totalCount: 0,
  pendingCount: 0,
  pendingReviewCount: 0,
  resolvedCount: 0
})

// 状态映射
const statusMap = {
  0: { text: '待维修', type: 'danger' },
  1: { text: '已维修', type: 'success' },
  2: { text: '待审核', type: 'warning' },
  3: { text: '不通过', type: 'info' }
}

// 信息卡片状态映射
const infoStatusMap = {
  0: { text: '待维修', color: '#ff4d4f', bg: 'rgba(255,77,79,0.08)' },
  1: { text: '已维修', color: '#52c41a', bg: 'rgba(82,196,26,0.08)' },
  2: { text: '待审核', color: '#faad14', bg: 'rgba(250,173,20,0.08)' },
  3: { text: '不通过', color: '#8c8c8c', bg: 'rgba(140,140,140,0.08)' }
}

// 获取状态文本
function getStatusText(status) {
  return statusMap[status]?.text || '未知'
}

// 获取状态类型
function getStatusType(status) {
  return statusMap[status]?.type || 'info'
}

// 获取指定状态的数量
function getStatusCount(status) {
  return latestIssues.value.filter(item => item.status === status).length
}

// 获取指定状态的百分比
function getStatusPercentage(status) {
  const total = latestIssues.value.length
  if (total === 0) return 0
  const count = getStatusCount(status)
  return Math.round((count / total) * 100)
}

// 获取处理效率（已维修 + 待审核）/ 总数
function getProcessingRate() {
  const total = statistics.value.totalCount
  if (total === 0) return 0
  const processed = statistics.value.resolvedCount + statistics.value.pendingReviewCount
  return Math.round((processed / total) * 100)
}

// 获取解决率（已维修 / 总数）
function getResolutionRate() {
  const total = statistics.value.totalCount
  if (total === 0) return 0
  return Math.round((statistics.value.resolvedCount / total) * 100)
}

// 获取当前月份隐患数量
function getCurrentMonthCount() {
  const currentMonth = new Date().toISOString().substring(0, 7)
  return monthlyData.value[currentMonth] || 0
}

// 获取月度变化文本
function getMonthChangeText() {
  const current = getCurrentMonthCount()
  const lastMonth = getLastMonthCount()
  if (current > lastMonth) {
    return `+${current - lastMonth}`
  } else if (current < lastMonth) {
    return `${current - lastMonth}`
  }
  return '持平'
}

// 获取月度变化样式类
function getMonthChangeClass() {
  const current = getCurrentMonthCount()
  const lastMonth = getLastMonthCount()
  if (current > lastMonth) return 'change-up'
  if (current < lastMonth) return 'change-down'
  return 'change-stable'
}

// 获取上个月隐患数量
function getLastMonthCount() {
  const lastMonth = new Date()
  lastMonth.setMonth(lastMonth.getMonth() - 1)
  const lastMonthStr = lastMonth.toISOString().substring(0, 7)
  return monthlyData.value[lastMonthStr] || 0
}

// 获取平均月度隐患数量
function getAverageMonthlyCount() {
  const months = getRecentMonths()
  const total = months.reduce((sum, month) => sum + month.count, 0)
  return Math.round(total / months.length)
}

// 获取最近6个月数据
function getRecentMonths() {
  const months = []
  const currentDate = new Date()
  
  for (let i = 5; i >= 0; i--) {
    const date = new Date(currentDate)
    date.setMonth(date.getMonth() - i)
    const monthStr = date.toISOString().substring(0, 7)
    const count = monthlyData.value[monthStr] || 0
    
    months.push({
      period: monthStr.substring(5), // 只显示月份
      fullPeriod: monthStr,
      count: count
    })
  }
  
  return months
}

// 获取柱状图高度百分比
function getBarHeight(count) {
  const months = getRecentMonths()
  const maxCount = Math.max(...months.map(m => m.count), 1)
  return (count / maxCount) * 100
}

// 获取柱状图样式类
function getBarClass(count) {
  if (count === 0) return 'bar-empty'
  if (count <= 2) return 'bar-low'
  if (count <= 5) return 'bar-medium'
  return 'bar-high'
}

// 获取高峰月份
function getPeakMonth() {
  const months = getRecentMonths()
  const maxMonth = months.reduce((max, month) => 
    month.count > max.count ? month : max
  )
  return maxMonth.count > 0 ? `${maxMonth.period}月 (${maxMonth.count}个)` : '无数据'
}

// 获取最佳月份（隐患最少）
function getBestMonth() {
  const months = getRecentMonths()
  const minMonth = months.reduce((min, month) => 
    month.count < min.count ? month : min
  )
  return `${minMonth.period}月 (${minMonth.count}个)`
}

// 获取趋势状态
function getTrendStatus() {
  const months = getRecentMonths()
  if (months.length < 2) return '数据不足'
  
  const recent = months.slice(-3).map(m => m.count)
  const earlier = months.slice(0, 3).map(m => m.count)
  
  const recentAvg = recent.reduce((sum, count) => sum + count, 0) / recent.length
  const earlierAvg = earlier.reduce((sum, count) => sum + count, 0) / earlier.length
  
  if (recentAvg > earlierAvg * 1.1) return '上升趋势'
  if (recentAvg < earlierAvg * 0.9) return '下降趋势'
  return '平稳趋势'
}

// 获取区域名称
function getRegionName(id) {
  const flatRegions = flattenRegionList(regionList.value)
  return flatRegions.find(region => region.id == id)?.name || id
}

// 扁平化区域列表
function flattenRegionList(nodes) {
  let result = []
  nodes.forEach(node => {
    result.push(node)
    if (node.children && node.children.length > 0) {
      result = result.concat(flattenRegionList(node.children))
    }
  })
  return result
}

// 获取数据
async function getData() {
  loading.value = true
  try {
    const response = await listInformation({ pageSize: 1000 })
    const data = response.rows || []
    
    console.log('获取到的原始数据:', data)
    console.log('数据总数:', data.length)
    
    // 统计有检测时间的数据
    const dataWithTime = data.filter(item => item.detectionTime)
    console.log('有检测时间的数据数量:', dataWithTime.length)
    
    // 计算统计数据
    statistics.value.totalCount = data.length
    statistics.value.pendingReviewCount = data.filter(item => item.status === 2).length // 待审核
    statistics.value.resolvedCount = data.filter(item => item.status === 1).length // 已维修
    statistics.value.pendingCount = data.filter(item => item.status === 0 || item.status === 3).length // 待维修 + 不通过
    
    // 调试信息
    const pendingCount = data.filter(item => item.status === 0).length
    const rejectedCount = data.filter(item => item.status === 3).length
    console.log('待维修数量:', pendingCount)
    console.log('不通过数量:', rejectedCount)
    console.log('待处理总数(待维修+不通过):', statistics.value.pendingCount)
    
    console.log('统计数据:', statistics.value)
    
    // 获取最新10条记录
    latestIssues.value = data.slice(0, 10)
    
    // 计算月度数据
    calculateMonthlyData(data)
    
    // 初始化折线图
    nextTick(() => {
      initTrendChart(data)
    })
  } catch (error) {
    console.error('获取数据失败:', error)
    proxy.$message.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}


// 计算月度数据
function calculateMonthlyData(data) {
  const monthCount = {}
  
  data.forEach(item => {
    if (item.detectionTime) {
      const month = item.detectionTime.substring(0, 7) // YYYY-MM
      monthCount[month] = (monthCount[month] || 0) + 1
    }
  })
  
  monthlyData.value = monthCount
  console.log('月度隐患统计:', monthCount)
}

// 初始化趋势图表
function initTrendChart(data) {
  if (!trendChart.value) return
  
  const chart = echarts.init(trendChart.value)
  
  // 按月份统计 - 统计每个月发现的安全隐患总数
  const monthCount = {}
  let validDataCount = 0
  
  data.forEach(item => {
    if (item.detectionTime) {
      const month = item.detectionTime.substring(0, 7) // YYYY-MM
      monthCount[month] = (monthCount[month] || 0) + 1
      validDataCount++
    }
  })
  
  console.log('月度隐患统计:', monthCount)
  console.log('有效数据数量:', validDataCount)
  
  // 如果没有有效的时间数据，显示提示
  if (validDataCount === 0) {
    const option = {
      title: {
        text: '暂无趋势数据',
        left: 'center',
        top: 'middle',
        textStyle: {
          color: '#999',
          fontSize: 14
        }
      }
    }
    chart.setOption(option)
    return
  }
  
  // 确保所有月份都有数据，没有数据的月份设为0
  const currentDate = new Date()
  const months = []
  const counts = []
  
  // 生成最近6个月的数据
  for (let i = 5; i >= 0; i--) {
    const date = new Date(currentDate)
    date.setMonth(date.getMonth() - i)
    const monthStr = date.toISOString().substring(0, 7)
    months.push(monthStr)
    counts.push(monthCount[monthStr] || 0)
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const data = params[0]
        return `${data.name}<br/>发现隐患数量: ${data.value}`
      }
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLabel: {
        formatter: function(value) {
          return value.substring(5) // 只显示月份 MM
        }
      }
    },
    yAxis: {
      type: 'value',
      minInterval: 1
    },
    series: [
      {
        name: '发现隐患数量',
        type: 'line',
        data: counts,
        smooth: true,
        areaStyle: {
          opacity: 0.3
        },
        itemStyle: {
          color: '#667eea'
        },
        lineStyle: {
          width: 3
        }
      }
    ]
  }
  
  chart.setOption(option)
}

// 获取区域数据
async function getRegionData() {
  try {
    const response = await listRegion()
    regionList.value = proxy.handleTree(response.data, 'id', 'parentId')
  } catch (error) {
    console.error('获取区域数据失败:', error)
  }
}

// 刷新数据
function refreshData() {
  getData()
}

// 查看详情
function viewDetail(row) {
  proxy.$router.push(`/information/information?view=${row.id}`)
}

// 跳转到信息管理页面
function goToInformation() {
  proxy.$router.push('/information/information')
}

// 导出数据
function exportData() {
  proxy.download(
    'information/information/export',
    {},
    `safety_issues_${new Date().getTime()}.xlsx`
  )
}

// 跳转到菜单管理页面
function goToMenuManagement() {
  proxy.$router.push('/system/menu')
}

// 格式化时间显示
function formatTime(timeStr) {
  if (!timeStr) return '暂无时间'
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date
  
  // 如果是今天
  if (diff < 24 * 60 * 60 * 1000 && date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  
  // 如果是昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  
  // 其他情况显示完整日期
  return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}

// 获取当前日期
function getCurrentDate() {
  const now = new Date()
  const options = { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric',
    weekday: 'long'
  }
  return now.toLocaleDateString('zh-CN', options)
}

// 获取用户数据
async function getUserData() {
  try {
    const response = await listUser({ pageSize: 1000 })
    userList.value = response.rows || []
  } catch (error) {
    console.error('获取用户数据失败:', error)
  }
}

// 获取请假数据
async function getLeaveData() {
  try {
    const response = await listLeave({ pageSize: 1000 })
    leaveList.value = response.rows || []
  } catch (error) {
    console.error('获取请假数据失败:', error)
  }
}

// 检查请假状态并生成通知
function checkLeaveStatus() {
  const notifications = []
  const now = new Date()
  
  leaveList.value.forEach(leave => {
    // 只检查已通过的请假申请
    if (leave.status !== 0) {
      return
    }
    
    const user = userList.value.find(u => u.userId === leave.cLeaveUser?.userId)
    if (!user) return
    
    const leaveStartTime = new Date(leave.leaveTime)
    const leaveEndTime = new Date(leave.backTime)
    
    // 检查时间是否有效
    if (isNaN(leaveEndTime.getTime())) {
      return
    }
    
    // 检查是否应该开始请假但用户状态还是正常
    if (now >= leaveStartTime && now <= leaveEndTime && user.status === '0') {
      const notificationId = `start_${leave.id}_${user.userId}`
      if (!dismissedNotifications.value.has(notificationId)) {
        notifications.push({
          id: notificationId,
          type: 'leave-start',
          icon: 'time',
          message: `${user.nickName || user.userName} 已经请假了，请将他的状态设置为请假中`,
          actionText: '设置请假中',
          userId: user.userId,
          leaveId: leave.id,
          action: 'setOnLeave'
        })
      }
    }
    
    // 检查是否应该销假但用户状态还是请假中
    if (now > leaveEndTime && user.status === '2') {
      const notificationId = `end_${leave.id}_${user.userId}`
      if (!dismissedNotifications.value.has(notificationId)) {
        notifications.push({
          id: notificationId,
          type: 'leave-end',
          icon: 'user',
          message: `${user.nickName || user.userName} 已经销假了，请将他的状态设置为正常`,
          actionText: '设置正常',
          userId: user.userId,
          leaveId: leave.id,
          action: 'setNormal'
        })
      }
    }
  })
  
  leaveNotifications.value = notifications
}

// 处理状态更新
async function handleStatusUpdate(notification) {
  try {
    const user = userList.value.find(u => u.userId === notification.userId)
    if (!user) {
      proxy.$modal.msgError('用户不存在')
      return
    }
    
    let newStatus
    let statusText
    
    if (notification.action === 'setOnLeave') {
      newStatus = '2' // 请假中
      statusText = '请假中'
    } else if (notification.action === 'setNormal') {
      newStatus = '0' // 正常
      statusText = '正常'
    }
    
    // 更新用户状态
    const updateData = {
      ...user,
      status: newStatus
    }
    
    await updateUser(updateData)
    
    // 如果是设置正常状态（销假），同时更新对应的请假申请状态为已销假
    if (notification.action === 'setNormal' && notification.leaveId) {
      try {
        const leave = leaveList.value.find(l => l.id === notification.leaveId)
        if (leave) {
          const leaveUpdateData = {
            ...leave,
            status: 3 // 已销假状态
          }
          await updateLeave(leaveUpdateData)
          
          // 更新本地请假数据
          const leaveIndex = leaveList.value.findIndex(l => l.id === notification.leaveId)
          if (leaveIndex !== -1) {
            leaveList.value[leaveIndex].status = 3
          }
        }
      } catch (error) {
        console.error('更新请假申请状态失败:', error)
        // 即使请假申请更新失败，用户状态更新成功也要继续
      }
    }
    
    // 更新本地用户数据
    const userIndex = userList.value.findIndex(u => u.userId === notification.userId)
    if (userIndex !== -1) {
      userList.value[userIndex].status = newStatus
    }
    
    // 移除通知
    leaveNotifications.value = leaveNotifications.value.filter(n => n.id !== notification.id)
    
    const successMessage = notification.action === 'setNormal' 
      ? `已将 ${user.nickName || user.userName} 的状态设置为${statusText}，并将请假申请标记为已销假`
      : `已将 ${user.nickName || user.userName} 的状态设置为${statusText}`
    
    proxy.$modal.msgSuccess(successMessage)
    
    // 重新检查状态
    checkLeaveStatus()
  } catch (error) {
    console.error('更新用户状态失败:', error)
    proxy.$modal.msgError('更新用户状态失败')
  }
}

// 忽略通知
function dismissNotification(notificationId) {
  dismissedNotifications.value.add(notificationId)
  leaveNotifications.value = leaveNotifications.value.filter(n => n.id !== notificationId)
  
  // 将忽略的通知保存到本地存储
  const dismissed = Array.from(dismissedNotifications.value)
  localStorage.setItem('dismissedLeaveNotifications', JSON.stringify(dismissed))
}

// 从本地存储加载已忽略的通知
function loadDismissedNotifications() {
  try {
    const dismissed = localStorage.getItem('dismissedLeaveNotifications')
    if (dismissed) {
      dismissedNotifications.value = new Set(JSON.parse(dismissed))
    }
  } catch (error) {
    console.error('加载已忽略通知失败:', error)
  }
}


onMounted(async () => {
  loadDismissedNotifications()
  
  // 并行加载所有数据
  await Promise.all([
    getRegionData(),
    getData(),
    getUserData(),
    getLeaveData()
  ])
  
  // 确保所有数据加载完成后再进行首次检查
  setTimeout(() => {
    checkLeaveStatus()
  }, 1000)
  
  // 设置定时检查请假状态（每1分钟检查一次）
  setInterval(() => {
    checkLeaveStatus()
  }, 1 * 60 * 1000)
})

</script>

<style scoped lang="scss">
@import '@/assets/styles/dashboard-home.scss';
</style>

